<template>
  <div class="product-management-container agri-page-container">
    <div class="page-header agri-page-header">
      <div class="page-title agri-page-title">
        <el-icon><Goods /></el-icon>
        <span>商品管理</span>
      </div>
      <div class="page-actions agri-page-actions">
        <el-button type="primary" @click="handleAddProduct">
          <el-icon><Plus /></el-icon> 添加商品
        </el-button>
      </div>
    </div>

    <!-- 商品筛选卡片 -->
    <el-card class="filter-card agri-card">
      <div class="filter-container">
        <el-input
          v-model="searchQuery"
          placeholder="搜索商品名称/编号"
          clearable
          class="filter-item"
          @input="handleFilterChange"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <el-select
          v-model="filterCategory"
          placeholder="商品分类"
          clearable
          class="filter-item"
          @change="handleFilterChange"
        >
          <el-option
            v-for="item in categoryOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>

        <el-select
          v-model="filterStatus"
          placeholder="商品状态"
          clearable
          class="filter-item"
          @change="handleFilterChange"
        >
          <el-option label="已上架" :value="1" />
          <el-option label="已下架" :value="0" />
        </el-select>

        <div class="filter-actions">
          <el-button type="primary" @click="handleFilterChange">筛选</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </div>
      </div>
    </el-card>

    <!-- 商品列表/卡片 -->
    <el-card class="product-list-card agri-card" v-loading="loading">
     

      <!-- 表格视图 -->
      <div v-if="viewMode === 'table'" class="agri-table-wrapper">
        <el-table
          ref="productTableRef"
          :data="paginatedProducts"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="productCode" label="商品编号" width="120" />
          <el-table-column label="商品信息" min-width="200">
            <template #default="scope">
              <div class="product-info-cell">
                <img :src="getImageUrl(scope.row.image)" class="product-image-thumbnail" />
                <div class="product-details">
                  <div class="product-name">{{ scope.row.name }}</div>
                  <div class="product-meta">
                    <el-tag size="small">{{ getCategoryLabel(scope.row.category) }}</el-tag>
                    <span>库存: {{ scope.row.stock }} {{ scope.row.unit }}</span>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="价格" prop="price" min-width="100">
            <template #default="scope">
              ¥{{ scope.row.price }} / {{ scope.row.unit }}
            </template>
          </el-table-column>
          
          <el-table-column label="养分含量" prop="nutrientContent" min-width="120" />
          
          <el-table-column label="适用作物" min-width="150">
            <template #default="scope">
              <el-space wrap>
                <el-tag 
                  v-for="crop in scope.row.suitableCropsList || []" 
                  :key="crop" 
                  size="small"
                  type="success"
                >
                  {{ getCropLabel(crop) }}
                </el-tag>
                <span v-if="!scope.row.suitableCropsList || scope.row.suitableCropsList.length === 0">
                  无数据
                </span>
              </el-space>
            </template>
          </el-table-column>
          
          <el-table-column label="品质证书" min-width="150">
            <template #default="scope">
              <el-space wrap>
                <el-tag 
                  v-for="cert in scope.row.certificatesList || []" 
                  :key="cert" 
                  size="small"
                  type="info"
                >
                  {{ getCertificateLabel(cert) }}
                </el-tag>
                <span v-if="!scope.row.certificatesList || scope.row.certificatesList.length === 0">
                  无数据
                </span>
              </el-space>
            </template>
          </el-table-column>
          
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)" size="small">
                {{ getStatusLabel(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
        <div class="agri-operations">
          <el-button
                v-if="scope.row.status === 0"
                type="success"
                size="small"
                @click="handleProductStatus(scope.row, 1)"
              >
                上架
              </el-button>
              <el-button
                v-if="scope.row.status === 1"
                type="warning"
                size="small"
                @click="handleProductStatus(scope.row, 0)"
              >
                下架
              </el-button>
              <el-button
                type="primary"
                size="small"
                @click="handleEditProduct(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleDeleteProduct(scope.row)"
              >
                删除
              </el-button>
            
        </div>
      </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 卡片视图 -->
      <div v-else class="product-grid">
        <div v-if="filteredProducts.length === 0" class="empty-data">
          <el-empty description="暂无商品数据" />
        </div>
        
        <div v-else>
          <el-row :gutter="20">
            <el-col :span="12" v-for="product in paginatedProducts" :key="product.id">
              <el-card class="product-card agri-card">
                <div class="product-image">
                  <img :src="product.image || defaultImage" alt="Product Image" />
                </div>
                <div class="product-details">
                  <h3 class="product-name">{{ product.name }}</h3>
                  <div class="product-meta">
                    <el-tag size="small">{{ getCategoryLabel(product.category) }}</el-tag>
                    <span>库存: {{ product.stock }} {{ product.unit }}</span>
                  </div>
                  <p class="product-description">{{ product.description }}</p>
                  <div class="product-actions">
                    <el-button type="primary" @click="handleEditProduct(product)">编辑</el-button>
                    <el-button type="danger" @click="handleDeleteProduct(product)">删除</el-button>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </div>

      <!-- 分页器 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="prev, pager, next, jumper, total"
          :total="filteredProducts.length"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑商品对话框 -->
    <div class="agri-dialog-wrapper">
      <el-dialog
        v-model="productDialogVisible"
        :title="isEdit ? '编辑商品' : '添加商品'"
        width="650px"
      >
        <el-form
          ref="productFormRef"
          :model="productForm"
          :rules="productRules"
          label-width="100px"
          label-position="right"
        >
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="productForm.name" placeholder="请输入商品名称" />
          </el-form-item>

          <el-form-item label="商品分类" prop="category">
            <el-select v-model="productForm.category" placeholder="请选择商品分类" style="width: 100%">
              <el-option
                v-for="item in categoryOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="商品价格" prop="price">
            <el-input-number
              v-model="productForm.price"
              :precision="2"
              :step="0.1"
              :min="0"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="计量单位" prop="unit">
            <el-input v-model="productForm.unit" placeholder="例如: kg, 箱, 件" />
          </el-form-item>

          <el-form-item label="库存数量" prop="stock">
            <el-input-number
              v-model="productForm.stock"
              :min="0"
              :precision="0"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="商品图片" prop="image">
            <el-upload
              class="product-image-uploader"
              action="#"
              :http-request="handleImageUpload"
              :show-file-list="false"
              :before-upload="beforeImageUpload"
            >
              <img v-if="productForm.image" :src="productForm.image" class="uploaded-image" />
              <el-icon v-else class="image-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div class="upload-tip">建议上传尺寸: 800x800 像素 JPG/PNG 格式图片</div>
          </el-form-item>

          <el-form-item label="商品描述" prop="description">
            <el-input
              v-model="productForm.description"
              type="textarea"
              :rows="4"
              placeholder="请输入商品描述"
            />
          </el-form-item>

          <el-form-item label="产地" prop="origin">
            <el-input v-model="productForm.origin" placeholder="请输入商品产地" />
          </el-form-item>

          <el-form-item label="生产日期" prop="productionDate">
            <el-date-picker
              v-model="productForm.productionDate"
              type="date"
              placeholder="请选择生产日期"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="保质期(天)" prop="shelfLife">
            <el-input-number
              v-model="productForm.shelfLife"
              :min="1"
              :precision="0"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="品质证书" prop="certificates">
            <el-select
              v-model="productForm.certificates"
              multiple
              placeholder="请选择品质证书"
              style="width: 100%"
            >
              <el-option label="肥料登记证" value="fertilizer_registration" />
              <el-option label="有机肥料认证" value="organic_fertilizer" />
              <el-option label="无公害肥料" value="pollution_free" />
              <el-option label="质量管理体系认证" value="iso9001" />
              <el-option label="产品质量检测报告" value="quality_test" />
              <el-option label="绿色环保认证" value="green_environmental" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="养分含量" prop="nutrientContent">
            <el-input v-model="productForm.nutrientContent" placeholder="例如: N:P:K=15:15:15" />
          </el-form-item>
          
          <el-form-item label="适用作物" prop="suitableCrops">
            <el-select
              v-model="productForm.suitableCrops"
              multiple
              placeholder="请选择适用作物"
              style="width: 100%"
            >
              <el-option label="水稻" value="rice" />
              <el-option label="小麦" value="wheat" />
              <el-option label="玉米" value="corn" />
              <el-option label="蔬菜" value="vegetable" />
              <el-option label="果树" value="fruit_tree" />
              <el-option label="茶叶" value="tea" />
              <el-option label="花卉" value="flowers" />
              <el-option label="经济作物" value="economic_crops" />
              <el-option label="通用" value="general" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="使用说明" prop="instructions">
            <el-input
              v-model="productForm.instructions"
              type="textarea"
              :rows="3"
              placeholder="请输入使用方法、用量等说明"
            />
          </el-form-item>

          <el-form-item label="上架状态" prop="status">
            <el-radio-group v-model="productForm.status">
              <el-radio :value="1">立即上架</el-radio>
              <el-radio :value="0">暂不上架</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="productDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitProductForm" :loading="submitting">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  Goods, Plus, Search, Delete, Edit, Grid, List
} from '@element-plus/icons-vue';
import { useSellerStore } from '../../store';
import { format } from 'date-fns';

// 状态管理
const sellerStore = useSellerStore();
const defaultImage = 'https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png';

// 列表数据和状态
const loading = ref(false);
const products = ref([]);
const selectedProducts = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const searchQuery = ref('');
const filterCategory = ref('');
const filterStatus = ref('');
const productTableRef = ref(null);
const viewMode = ref('table');

// 对话框控制
const productDialogVisible = ref(false);
const isEdit = ref(false);
const submitting = ref(false);

// 商品表单
const productFormRef = ref(null);
const productForm = reactive({
  id: '',
  productCode: '',
  name: '',
  category: '',
  price: 0,
  unit: 'kg',
  stock: 0,
  image: '',
  description: '',
  origin: '',
  productionDate: '',
  shelfLife: 30,
  certificates: [],
  status: 0,
  sales: 0,
  nutrientContent: '',
  suitableCrops: [],
  instructions: ''
});

// 商品分类选项
const categoryOptions = [
  { value: 'nitrogen', label: '氮肥' },
  { value: 'phosphate', label: '磷肥' },
  { value: 'potassium', label: '钾肥' },
  { value: 'compound', label: '复合肥' },
  { value: 'organic', label: '有机肥' },
  { value: 'microbial', label: '微生物肥料' },
  { value: 'foliar', label: '叶面肥' },
  { value: 'soil', label: '土壤调理剂' },
  { value: 'specialty', label: '专用肥料' },
  { value: 'other', label: '其他' }
];

// 表单验证规则
const productRules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格必须大于等于0', trigger: 'blur' }
  ],
  unit: [
    { required: true, message: '请输入计量单位', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入库存数量', trigger: 'blur' },
    { type: 'number', min: 0, message: '库存必须大于等于0', trigger: 'blur' }
  ],
  description: [
    { max: 500, message: '长度不能超过500个字符', trigger: 'blur' }
  ],
  origin: [
    { max: 50, message: '长度不能超过50个字符', trigger: 'blur' }
  ],
  shelfLife: [
    { type: 'number', min: 1, message: '保质期必须大于等于1天', trigger: 'blur' }
  ],
  nutrientContent: [
    { required: true, message: '请输入养分含量', trigger: 'blur' }
  ],
  suitableCrops: [
    { type: 'array', message: '请选择适用作物', trigger: 'change' }
  ],
  instructions: [
    { required: true, message: '请输入使用说明', trigger: 'blur' },
    { max: 500, message: '长度不能超过500个字符', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择上架状态', trigger: 'change' }
  ]
};

// 过滤后的商品列表
const filteredProducts = computed(() => {
  if (!products.value.length) return [];
  
  let result = [...products.value];
  
  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    result = result.filter(product => 
      product.name.toLowerCase().includes(query) || 
      product.productCode.toLowerCase().includes(query)
    );
  }
  
  // 分类过滤
  if (filterCategory.value) {
    result = result.filter(product => product.category === filterCategory.value);
  }
  
  // 状态过滤
  if (filterStatus.value) {
    result = result.filter(product => product.status === filterStatus.value);
  }
  
  return result;
});

// 分页后的商品列表
const paginatedProducts = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredProducts.value.slice(start, end);
});

// 获取分类标签
const getCategoryLabel = (category) => {
  const option = categoryOptions.find(item => item.value === category);
  return option ? option.label : category;
};

// 获取作物标签
const getCropLabel = (crop) => {
  const cropMap = {
    'rice': '水稻',
    'wheat': '小麦',
    'corn': '玉米',
    'vegetable': '蔬菜',
    'fruit_tree': '果树',
    'tea': '茶叶',
    'flowers': '花卉',
    'economic_crops': '经济作物',
    'general': '通用'
  };
  return cropMap[crop] || crop;
};

// 获取状态类型样式
const getStatusType = (status) => {
  const types = {
    1: 'success',  // 已上架
    0: 'info'      // 已下架
  };
  return types[status] || 'info';
};

// 获取状态标签
const getStatusLabel = (status) => {
  const labels = {
    1: '已上架',
    0: '已下架'
  };
  return labels[status] || '未知状态';
};

// 获取证书标签
const getCertificateLabel = (cert) => {
  const certMap = {
    'fertilizer_registration': '肥料登记证',
    'organic_fertilizer': '有机肥料认证',
    'pollution_free': '无公害肥料',
    'iso9001': '质量管理体系认证',
    'quality_test': '产品质量检测报告',
    'green_environmental': '绿色环保认证'
  };
  return certMap[cert] || cert;
};

// 筛选变化
const handleFilterChange = () => {
  currentPage.value = 1;
};

// 重置筛选条件
const resetFilter = () => {
  searchQuery.value = '';
  filterCategory.value = '';
  filterStatus.value = '';
  handleFilterChange();
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
};

// 表格选择变化
const handleSelectionChange = (val) => {
  selectedProducts.value = val;
};

// 批量操作处理
const handleBatchAction = (action) => {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning('请至少选择一个商品');
    return;
  }
  
  let confirmMessage = '';
  let successMessage = '';
  let status = null;
  
  switch(action) {
    case 'active':
      confirmMessage = '确定要批量上架选中的商品吗？';
      successMessage = '批量上架成功';
      status = 1;
      break;
    case 'inactive':
      confirmMessage = '确定要批量下架选中的商品吗？';
      successMessage = '批量下架成功';
      status = 0;
      break;
    case 'delete':
      confirmMessage = '确定要批量删除选中的商品吗？此操作不可恢复！';
      successMessage = '批量删除成功';
      break;
    default:
      return;
  }
  
  ElMessageBox.confirm(
    confirmMessage,
    '批量操作',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      loading.value = true;
      
      // 获取所有选中商品的ID
      const productIds = selectedProducts.value.map(item => item.id);
      
      if (action === 'delete') {
        // 批量删除
        await sellerStore.deleteProducts(productIds);
      } else {
        // 批量更新状态
        await sellerStore.updateProductsStatus(productIds, status);
      }
      
      ElMessage.success(successMessage);
      
      // 刷新商品列表
      fetchProducts();
      
      // 清空选择
      if (productTableRef.value) {
        productTableRef.value.clearSelection();
      }
    } catch (error) {
      console.error('批量操作失败', error);
      ElMessage.error('批量操作失败: ' + (error.message || '未知错误'));
    } finally {
      loading.value = false;
    }
  }).catch(() => {});
};

// 商品状态处理
const handleProductStatus = (product, status) => {
  const actionText = status === 1 ? '上架' : '下架';
  
  ElMessageBox.confirm(
    `确定要${actionText}商品【${product.name}】吗？`,
    '修改商品状态',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      loading.value = true;
      
      // 更新商品状态
      await sellerStore.updateProductStatus(product.id, status);
      
      ElMessage.success(`商品${actionText}成功`);
      
      // 刷新商品列表
      fetchProducts();
    } catch (error) {
      console.error(`商品${actionText}失败`, error);
      ElMessage.error(`商品${actionText}失败: ` + (error.message || '未知错误'));
    } finally {
      loading.value = false;
    }
  }).catch(() => {});
};

// 添加商品
const handleAddProduct = () => {
  isEdit.value = false;
  resetProductForm();
  
  // 生成商品编号
  productForm.productCode = 'P' + Date.now().toString().slice(-8);
  
  productDialogVisible.value = true;
};

// 编辑商品
const handleEditProduct = (product) => {
  console.log('编辑商品，原始数据:', product);
  isEdit.value = true;
  resetProductForm();
  
  try {
    // 深拷贝商品数据，避免直接修改原始数据
    const productCopy = JSON.parse(JSON.stringify(product));
    
    // 填充商品数据
    Object.keys(productForm).forEach(key => {
      if (key in productCopy) {
        // 处理特殊字段
        if (key === 'certificates') {
          // 优先使用certificatesList字段
          if (Array.isArray(productCopy.certificatesList)) {
            productForm[key] = [...productCopy.certificatesList];
          } else if (typeof productCopy[key] === 'string') {
            try {
              productForm[key] = productCopy[key] ? JSON.parse(productCopy[key]) : [];
            } catch (e) {
              console.error(`解析${key}字段失败:`, e);
              productForm[key] = [];
            }
          } else {
            productForm[key] = [];
          }
        } else if (key === 'suitableCrops') {
          // 优先使用suitableCropsList字段
          if (Array.isArray(productCopy.suitableCropsList)) {
            productForm[key] = [...productCopy.suitableCropsList];
          } else if (typeof productCopy[key] === 'string') {
            try {
              productForm[key] = productCopy[key] ? JSON.parse(productCopy[key]) : [];
            } catch (e) {
              console.error(`解析${key}字段失败:`, e);
              productForm[key] = [];
            }
          } else {
            productForm[key] = [];
          }
        } else if (key === 'status' || key === 'stock') {
          // 确保整数类型正确
          productForm[key] = typeof productCopy[key] === 'string' ? 
                          parseInt(productCopy[key]) : 
                          (typeof productCopy[key] === 'number' ? productCopy[key] : 0);
        } else if (key === 'price') {
          // 确保浮点数类型正确
          productForm[key] = typeof productCopy[key] === 'string' ? 
                          parseFloat(productCopy[key]) : 
                          (typeof productCopy[key] === 'number' ? productCopy[key] : 0);
        } else if (key === 'productionDate' && productCopy[key]) {
          // 处理日期字段
          if (productCopy[key] instanceof Date) {
            productForm[key] = productCopy[key];
          } else {
            try {
              productForm[key] = new Date(productCopy[key]);
              // 检查日期是否有效
              if (isNaN(productForm[key].getTime())) {
                console.warn('无效的日期值:', productCopy[key]);
                productForm[key] = null;
              }
            } catch (e) {
              console.error('日期转换失败:', e);
              productForm[key] = null;
            }
          }
        } else if (key === 'image') {
          // 确保图片URL是完整的
          productForm[key] = productCopy[key] ? getImageUrl(productCopy[key]) : '';
        } else {
          productForm[key] = productCopy[key];
        }
      }
    });
    
    console.log('处理后的表单数据:', productForm);
  } catch (error) {
    console.error('填充表单数据时出错:', error);
    ElMessage.error('加载商品数据失败: ' + (error.message || '未知错误'));
  }
  
  productDialogVisible.value = true;
};

// 删除商品
const handleDeleteProduct = (product) => {
  ElMessageBox.confirm(
    `确定要删除商品【${product.name}】吗？此操作不可恢复！`,
    '删除商品',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      loading.value = true;
      
      // 删除商品
      await sellerStore.deleteProduct(product.id);
      
      ElMessage.success('商品删除成功');
      
      // 刷新商品列表
      fetchProducts();
    } catch (error) {
      console.error('商品删除失败', error);
      ElMessage.error('商品删除失败: ' + (error.message || '未知错误'));
    } finally {
      loading.value = false;
    }
  }).catch(() => {});
};

// 图片上传前验证
const beforeImageUpload = (file) => {
  // 验证文件类型和大小
  const isJPG = file.type === 'image/jpeg';
  const isPNG = file.type === 'image/png';
  const isLt1M = file.size / 1024 / 1024 < 1;

  if (!isJPG && !isPNG) {
    ElMessage.error('上传图片只能是 JPG 或 PNG 格式!');
    return false;
  }
  if (!isLt1M) {
    ElMessage.error('上传图片大小不能超过 1MB!');
    return false;
  }
  return true;
};

// 获取商品图片URL
const getImageUrl = (image) => {
  if (!image) {
    return '/default-product.png'; // 默认图片
  }
  
  console.log('原始图片链接:', image);
  
  // 如果已经是完整URL，直接返回
  if (image.startsWith('http://') || image.startsWith('https://')) {
    return image;
  }
  
  // 如果是base64数据，直接返回
  if (image.startsWith('data:image/')) {
    return image;
  }
  
  // 如果是相对路径，拼接API地址 (确保前端能正确解析后端返回的路径)
  if (image.startsWith('/')) {
    console.log('处理图片路径:', image);
    
    const apiBaseUrl = import.meta.env.VITE_API_BASE_URL || '/api';
    
    // 确保路径正确（根据实际的静态资源配置规则）
    const path = image.startsWith('/file/') ? image : `/file${image}`;
    const url = `${apiBaseUrl}${path}`;
    console.log('最终图片URL:', url);
    return url;
  }
  
  // 其他情况，可能是相对路径但没有前导斜杠
  const apiBaseUrl = import.meta.env.VITE_API_BASE_URL || '/api';
  const url = `${apiBaseUrl}/file/${image}`;
  console.log('最终图片URL:', url);
  return url;
};

// 处理图片上传
const handleImageUpload = (options) => {
  const file = options.file;
  
  // 验证文件类型和大小
  const isJPG = file.type === 'image/jpeg';
  const isPNG = file.type === 'image/png';
  const isLt1M = file.size / 1024 / 1024 < 1;

  if (!isJPG && !isPNG) {
    ElMessage.error('上传图片只能是 JPG 或 PNG 格式!');
    return;
  }
  if (!isLt1M) {
    ElMessage.error('上传图片大小不能超过 1MB!');
    return;
  }
  
  // 使用URL.createObjectURL创建临时URL
  const objectUrl = URL.createObjectURL(file);
  productForm.image = objectUrl;
  
  // 记录原始文件，用于后续上传
  productForm.imageFile = file;
  
  ElMessage.success('图片已预览，将在提交表单时上传');
};

// 提交商品表单
const submitProductForm = async () => {
  if (!productFormRef.value) {
    console.warn('表单引用不存在，无法提交');
    return;
  }
  
  await productFormRef.value.validate(async (valid) => {
    if (!valid) {
      console.warn('表单验证失败');
      return;
    }
    
    try {
      submitting.value = true;
      console.log('开始提交商品表单...');
      
      // 准备商品数据
      const productData = { ...productForm };
      console.log('处理前的商品数据:', productData);
      
      // 处理图片上传
      if (productForm.imageFile) {
        try {
          console.log('开始上传图片...');
          console.log('图片文件类型:', productForm.imageFile.type);
          console.log('图片文件大小:', productForm.imageFile.size);
          
          const response = await sellerStore.uploadProductImage(productForm.imageFile);
          console.log('图片上传响应:', response);
          
          if (response) {
            productData.image = response;
            console.log('设置图片URL:', productData.image);
          } else {
            throw new Error('图片上传失败: 未获取到有效的图片URL');
          }
        } catch (error) {
          console.error('图片上传错误:', error);
          ElMessage.error('图片上传失败: ' + (error.message || '未知错误'));
          submitting.value = false;
          return;
        }
      } else if (productData.image && productData.image.startsWith('blob:')) {
        // 如果有blob:URL格式的临时图片但没有文件对象，清除图片
        console.log('发现临时blob图片URL，将被清除:', productData.image);
        delete productData.image;
      } else {
        // 确保保留现有图片URL
        console.log('保留现有图片URL:', productData.image);
      }
      
      // 移除不需要的字段
      delete productData.imageFile;
      delete productData.productCode; // 移除前端生成的临时代码，让后端生成
      
      // 处理日期数据
      if (productData.productionDate) {
        // 将Date对象转换为指定格式的字符串 (yyyy-MM-dd HH:mm:ss)
        const date = new Date(productData.productionDate);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        
        productData.productionDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        console.log('格式化后的生产日期:', productData.productionDate);
      }
      
      // 与后端实体类字段匹配处理
      // 将certificates数组和suitableCrops数组处理为符合后端期望的格式
      if (Array.isArray(productData.certificates)) {
        productData.certificatesList = [...productData.certificates];
        delete productData.certificates;
      }
      
      if (Array.isArray(productData.suitableCrops)) {
        productData.suitableCropsList = [...productData.suitableCrops];
        delete productData.suitableCrops;
      }
      
      console.log('处理后的商品数据:', productData);
      
      if (isEdit.value) {
        // 更新商品
        console.log('更新商品ID:', productData.id);
        await sellerStore.updateProduct(productData);
        ElMessage.success('商品更新成功');
      } else {
        // 创建商品
        console.log('创建新商品');
        await sellerStore.createProduct(productData);
        ElMessage.success('商品添加成功');
      }
      
      // 关闭对话框
      productDialogVisible.value = false;
      
      // 刷新商品列表
      fetchProducts();
    } catch (error) {
      console.error('提交商品失败', error);
      console.error('错误详情:', error.stack);
      ElMessage.error('提交商品失败: ' + (error.message || '未知错误'));
    } finally {
      submitting.value = false;
    }
  });
};

// 重置商品表单
const resetProductForm = () => {
  // 重置为默认值
  Object.assign(productForm, {
    id: '',
    productCode: '',
    name: '',
    category: '',
    price: 0,
    unit: 'kg',
    stock: 0,
    image: '',
    description: '',
    origin: '',
    productionDate: '',
    shelfLife: 30,
    certificates: [],
    status: 0,
    sales: 0,
    nutrientContent: '',
    suitableCrops: [],
    instructions: ''
  });
  
  // 重置表单验证状态
  if (productFormRef.value) {
    productFormRef.value.resetFields();
  }
};

// 获取商品列表
const fetchProducts = async () => {
  loading.value = true;
  try {
    console.log('开始获取商品列表...');
    const productsData = await sellerStore.fetchProducts();
    console.log('获取到的商品列表数据:', productsData);
    
    // 确保所有必要的字段都存在且类型正确
    products.value = productsData.map(product => {
      return {
        ...product,
        // 确保价格和库存为数字
        price: typeof product.price === 'string' ? parseFloat(product.price) : (product.price || 0),
        stock: typeof product.stock === 'string' ? parseInt(product.stock) : (product.stock || 0),
        status: typeof product.status === 'string' ? parseInt(product.status) : (product.status || 0),
        // 确保数组字段正确
        suitableCrops: Array.isArray(product.suitableCrops) ? product.suitableCrops : 
                      (typeof product.suitableCrops === 'string' ? 
                        (product.suitableCrops ? JSON.parse(product.suitableCrops) : []) : []),
        certificates: Array.isArray(product.certificates) ? product.certificates : 
                     (typeof product.certificates === 'string' ? 
                       (product.certificates ? JSON.parse(product.certificates) : []) : [])
      };
    });
    console.log('处理后的商品列表数据:', products.value);
  } catch (error) {
    console.error('获取商品列表失败', error);
    ElMessage.error('获取商品列表失败: ' + (error.message || '未知错误'));
    products.value = [];
  } finally {
    loading.value = false;
  }
};

// 处理分页变化
const handlePageChange = (page) => {
  currentPage.value = page;
};

// 组件挂载时获取数据
onMounted(() => {
  try {
    console.log('ProductManagement组件开始挂载...');
    fetchProducts().then(() => {
      console.log('商品列表获取完成');
    }).catch(error => {
      console.error('获取商品列表失败', error);
    });
    console.log('ProductManagement组件挂载完成');
  } catch (error) {
    console.error('组件挂载过程中发生错误', error);
  }
});
</script>

<style scoped>
.product-management-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 22px;
  font-weight: bold;
  display: flex;
  align-items: center;
}

.page-title .el-icon {
  margin-right: 8px;
  font-size: 24px;
  color: var(--primary-color);
}

.page-actions {
  display: flex;
  gap: 10px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-container {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: center;
}

.filter-item {
  width: 220px;
}

.filter-actions {
  margin-left: auto;
}

.product-list-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-weight: bold;
  font-size: 16px;
}

.card-actions {
  display: flex;
  gap: 10px;
}

.product-image {
  width: 50px;
  height: 50px;
  border-radius: 4px;
  object-fit: cover;
}

.product-info-cell {
  display: flex;
  align-items: center;
}

.product-image-thumbnail {
  width: 50px;
  height: 50px;
  border-radius: 4px;
  object-fit: cover;
  margin-right: 10px;
}

.product-details {
  display: flex;
  flex-direction: column;
}

.product-name {
  font-weight: bold;
  margin-bottom: 4px;
}

.product-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  color: #606266;
}

.product-price {
  color: #f56c6c;
  font-weight: bold;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.product-image-uploader {
  width: 200px;
  height: 200px;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}

.product-image-uploader:hover {
  border-color: var(--primary-color);
}

.image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 30px;
  height: 30px;
}

.uploaded-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-tip {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-top: 5px;
}

.empty-data {
  padding: 40px 0;
  text-align: center;
}

.view-switch {
  margin-bottom: 10px;
}

.product-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.product-card {
  width: calc(33.33% - 20px);
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.product-card img {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 4px;
  margin-bottom: 10px;
}

.product-card h3 {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 5px;
}

.product-card .product-meta {
  font-size: 14px;
  color: #606266;
}

.product-card .product-actions {
  margin-top: 10px;
  display: flex;
  justify-content: center;
  gap: 10px;
}

.product-card .product-actions button {
  padding: 8px 16px;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .filter-container {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-item {
    width: 100%;
  }
  
  .filter-actions {
    width: 100%;
    display: flex;
    justify-content: flex-end;
    margin-top: 10px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .card-actions {
    width: 100%;
    justify-content: flex-end;
  }
}
</style> 